package com.salton123.charging.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;

import com.salton123.charging.Consts;
import com.salton123.charging.receiver.BatteryStatusReceiver;
import com.salton123.charging.receiver.ReStarter;
import com.salton123.charging.util.PrefsUtils;
import com.salton123.log.XLog;
import com.salton123.soulove.lib_demo.R;

import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationCompat.Builder;

/**
 * User: wujinsheng1@yy.com
 * Date: 2020/9/30 16:44
 * ModifyTime: 16:44
 * Description:
 */
public class SoundService extends Service {
    public static final String SELF_RESTART = "com.salton123.chargingtone.self_restart";
    private BatteryStatusReceiver mBatteryStatusReceiver;
    private Timer timer;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static void start(Context context) {
        start(context, false);
    }

    public static final String TAG = "SoundService";

    public static void start(Context context, boolean z) {
        XLog.d(TAG, "启动【音频服务】");
        Intent intent = new Intent(context, SoundService.class);
        intent.putExtra(SELF_RESTART, z);
        if (!PrefsUtils.get().getBoolean(Consts.KEY_ALWAYS_KEEP_RUNNING, false) || Build.VERSION.SDK_INT < 26) {
            context.startService(intent);
        } else {
            context.startForegroundService(intent);
        }
    }

    public void onCreate() {
        super.onCreate();
    }

    public int onStartCommand(Intent intent, int i, int i2) {
        if (intent.getBooleanExtra(SELF_RESTART, false)) {
            XLog.d(TAG, "【音频服务】已完成自动重启");
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.ACTION_POWER_CONNECTED");
        intentFilter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED");
        intentFilter.addAction("android.intent.action.BATTERY_CHANGED");
        intentFilter.addAction("android.intent.action.BATTERY_LOW");
        BatteryStatusReceiver batteryStatusReceiver = new BatteryStatusReceiver();
        this.mBatteryStatusReceiver = batteryStatusReceiver;
        registerReceiver(batteryStatusReceiver, intentFilter);
        if (PrefsUtils.get().getBoolean(Consts.KEY_ALWAYS_KEEP_RUNNING, false) && Build.VERSION.SDK_INT >= 26) {
            XLog.d(TAG, "【应用常驻内存】，发送【正在运行】的通知");
            String str = "keep_in_background";
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                    .createNotificationChannel(new NotificationChannel(str, getString(R.string.app_in_running),
                            NotificationManager.IMPORTANCE_MIN));
            Builder builder = new Builder(this, str);
            str = "";
            startForeground(1, builder.setContentTitle(str).setContentText(str).build());
        }
        if (PrefsUtils.get().getBoolean(Consts.KEY_USE_FLOATING_SERVICE, false)) {
            showFloating();
        }
        Timer timer = new Timer();
        this.timer = timer;
        timer.schedule(new TimerTask() {
            public void run() {
                XLog.d(TAG, "【音频服务】 运行中");
            }
        }, 0, 60000);
        return Service.START_STICKY;
    }

    private void showFloating() {
        if (Build.VERSION.SDK_INT < 23 || Settings.canDrawOverlays(this)) {
            XLog.d(TAG, "【流氓后台】 显示 1x1 悬浮窗");
            WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            View view = new View(this);
            view.setBackgroundColor(0);
            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            if (Build.VERSION.SDK_INT >= 26) {
                layoutParams.type = 2038;
            } else {
                layoutParams.type = 2002;
            }
            layoutParams.flags = 56;
            layoutParams.format = -2;
            layoutParams.width = 1;
            layoutParams.height = 1;
            layoutParams.x = 0;
            layoutParams.y = 0;
            windowManager.addView(view, layoutParams);
            XLog.d(TAG, "【流氓后台】 悬浮窗已显示");
        }
    }

    public void onTaskRemoved(Intent intent) {
        restart(false);
        super.onTaskRemoved(intent);
    }

    public static final int EXACTLY = 1073741824;

    @SuppressLint("WrongConstant")
    private void restart(boolean isRestart) {
        BatteryStatusReceiver batteryStatusReceiver = this.mBatteryStatusReceiver;
        if (batteryStatusReceiver != null) {
            unregisterReceiver(batteryStatusReceiver);
        }
        Timer timer = this.timer;
        if (timer != null) {
            timer.cancel();
        }
        String str = SELF_RESTART;
        Intent intent;
        if (isRestart) {
            intent = new Intent();
            intent.putExtra(str, true);
            intent.setAction(ReStarter.RESTART);
            intent.setClass(this, ReStarter.class);
            sendBroadcast(intent);
            XLog.d(TAG, "【音频服务】 restart 进行自动重启");
        } else {
            intent = new Intent(getApplicationContext(), getClass());
            intent.setPackage(getPackageName());
            intent.putExtra(str, true);
            PendingIntent service = PendingIntent.getService(getApplicationContext(), 1, intent, EXACTLY);
            XLog.d(TAG, "【音频服务】 onTaskRemoved 1秒后重启");
            ((AlarmManager) getApplicationContext().getSystemService(NotificationCompat.CATEGORY_ALARM))
                    .set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, service);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        XLog.d(TAG, "【音频服务】onDestroy");
        restart(true);
    }
}
